﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Text;
using System.EnterpriseServices;
using System.Configuration;
using Models;
using Common;
using Langben.DAL;
using Langben.BLL;
using Langben.App.Models;
using System.Collections;
using System.Data;

namespace Langben.App.Controllers
{
    /// <summary>
    /// 入库退货表
    /// </summary>
    public class ts_accpayController : BaseController
    {

        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        [SupportFilter]
        public ActionResult Index()
        {
        
            return View();
        }
         /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        public ActionResult IndexSef()
        {

            return View();
        }

        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        [SupportFilter]
        public ActionResult GYSYFZKForm()
        { 
            return View();
        } 

        
        /// <summary>
        /// 往来帐调整
        /// </summary>
        /// <returns></returns>
        [SupportFilter]
        public ActionResult AdjustForm(string c_id,string c_name)
        {
            ViewData["c_id"] = c_id;
            ViewData["c_name"] = c_name;
            return View();
        }

         /// <summary>
        /// 创建
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [SupportFilter]
        public ActionResult AdjustForm(ts_accpay entity)
        {
            if (entity != null && ModelState.IsValid)
            {
                string currentPerson = GetCurrentPerson();
                //entity.CreateTime = DateTime.Now;
                //entity.CreatePerson = currentPerson;

                entity.Id = Result.GetNewId();
                entity.c_type = "调整";
                entity.f_credit = 0;
                entity.i_sign = "正常";
                string returnValue = string.Empty;
                if (m_BLL.Create(ref validationErrors, entity))
                {
                    LogClassModels.WriteServiceLog(Suggestion.InsertSucceed + "，入库退货表的信息的Id为" + entity.Id, "入库退货表"
                        );//写入日志 
                    return Json(Suggestion.InsertSucceed);
                }
                else
                {
                    if (validationErrors != null && validationErrors.Count > 0)
                    {
                        validationErrors.All(a =>
                        {
                            returnValue += a.ErrorMessage;
                            return true;
                        });
                    }
                    LogClassModels.WriteServiceLog(Suggestion.InsertFail + "，入库退货表的信息，" + returnValue, "入库退货表"
                        );//写入日志                      
                    return Json(Suggestion.InsertFail + returnValue); //提示插入失败
                }
            }

            return Json(Suggestion.InsertFail + "，请核对输入的数据的格式"); //提示输入的数据的格式不对 
        }


        /// <summary>
        /// 往来帐付款
        /// </summary>
        /// <returns></returns>
        [SupportFilter]
        public ActionResult PaymentForm(string c_id, string c_name)
        {
            ViewData["c_id"] = c_id;
            ViewData["c_name"] = c_name;
            return View();
        }



        /// <summary>
        /// 异步加载数据-供应商应付帐款
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="rows">每页显示的行数</param>
        /// <param name="order">排序字段</param>
        /// <param name="sort">升序asc（默认）还是降序desc</param>
        /// <param name="search">查询条件</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetGYSYFZKData(string search)
        {
            DateTime dtStart = Convert.ToDateTime("1900-10-10");
            DateTime dtEnd = DateTime.Now;
            string c_id = "";

            if (search != null)
            {
                string[] searchStr = search.Split('^');
                if (searchStr[0].Split('&')[1].ToString() != "")
                {
                    dtStart = Convert.ToDateTime(searchStr[0].Split('&')[1]);
                }
                if (searchStr[1].Split('&')[1].ToString() != "")
                {
                    dtEnd = Convert.ToDateTime(searchStr[1].Split('&')[1]);
                }
                if (searchStr[1].Split('&')[2].ToString() != "")
                {
                    c_id = searchStr[2].Split('&')[1];
                }
            }

            Hashtable ht = new Hashtable();
            SqlReadXml rx = new SqlReadXml();
            ht.Add("@dtStart", dtStart);
            ht.Add("@dtEnd", dtEnd);
            ht.Add("@c_id", c_id);
            DataSet ds = rx.ReaderDataSet("sel_GYSYFZK", ht);
            List<ts_accpay> accpayList = new List<ts_accpay>();
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                ts_accpay accpay = new ts_accpay();
                accpay.c_id = dr["c_id"].ToString();
                accpay.c_name = dr["c_name"].ToString();
                accpay.credit = dr["credit"].ToString();
                accpay.debit = dr["debit"].ToString();
                accpay.QMCount = dr["QMCount"].ToString();
                accpay.c_staff = dr["c_staff"].ToString();
                accpay.c_tele = dr["c_tele"].ToString();
                 
                accpayList.Add(accpay);
            }
            return Json(new datagrid
            {
                total = accpayList.Count(),
                rows = accpayList.Select(s => new
                {
                    c_id = s.c_id
                    ,
                    c_name = s.c_name
                    ,
                    credit = s.credit
                    ,
                    debit = s.debit
                    ,
                    QMCount = s.QMCount
                    ,
                    c_staff = s.c_staff
                    ,
                    c_tele = s.c_tele 
                }

                    )
            });
        }


        /// <summary>
        /// 异步加载数据-供应商进价历史
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="rows">每页显示的行数</param>
        /// <param name="order">排序字段</param>
        /// <param name="sort">升序asc（默认）还是降序desc</param>
        /// <param name="search">查询条件</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult PrintGYSYFZK(string search)
        {
            DateTime dtStart = Convert.ToDateTime("1900-10-10");
            DateTime dtEnd = DateTime.Now;
            string c_id = "";

            if (search != null)
            {
                string[] searchStr = search.Split('^');
                if (searchStr[0].Split('&')[1].ToString() != "")
                {
                    dtStart = Convert.ToDateTime(searchStr[0].Split('&')[1]);
                }
                if (searchStr[1].Split('&')[1].ToString() != "")
                {
                    dtEnd = Convert.ToDateTime(searchStr[1].Split('&')[1]);
                }
                if (searchStr[1].Split('&')[2].ToString() != "")
                {
                    c_id = searchStr[2].Split('&')[1];
                }
            }

            Hashtable ht = new Hashtable();
            SqlReadXml rx = new SqlReadXml();
            ht.Add("@dtStart", dtStart);
            ht.Add("@dtEnd", dtEnd);
            ht.Add("@c_id", c_id);
            DataSet ds = rx.ReaderDataSet("sel_GYSYFZK", ht);
            List<ts_accpay> accpayList = new List<ts_accpay>();
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                ts_accpay accpay = new ts_accpay();
                accpay.c_id = dr["c_id"].ToString();
                accpay.c_name = dr["c_name"].ToString();
                accpay.credit = dr["credit"].ToString();
                accpay.debit = dr["debit"].ToString();
                accpay.QMCount = dr["QMCount"].ToString();
                accpay.c_staff = dr["c_staff"].ToString();
                accpay.c_tele = dr["c_tele"].ToString();

                accpayList.Add(accpay);
            }

            //为打印提供html相关超文本内容。 
            StringBuilder sb = new StringBuilder();
            sb.Append("<table border=1 cellSpacing=0 cellPadding=1 width=\"100%\" style=\"border-collapse:collapse;font-size:12px;line-height:30px\"  bordercolor=\"#333333\"> ");
            sb.Append("<thead><tr>");
            sb.Append("<td><div align=\"center\">帐号</div></td>");
            sb.Append("<TD><div align=\"center\">名称</div></TD>");
            sb.Append("<TD><div align=\"center\">期初</div></TD>");
            sb.Append("<TD><div align=\"center\">本期发生</div></TD>");
            sb.Append("<TD><div align=\"center\">本期回款</div></TD>");
            sb.Append("<TD><div align=\"center\">期末</div></TD>");
            sb.Append("<TD><div align=\"center\">联系人</div></TD>");
            sb.Append("<TD><div align=\"center\">电话</div></TD>"); 
            sb.Append("</TR>");
            sb.Append("</thead>");
            sb.Append("<tbody>");


            foreach (ts_accpay item in accpayList)
            {
                sb.Append("<tr>");
                sb.Append("<td>");
                sb.Append(item.c_id);
                sb.Append("</td>");

                sb.Append("<td>");
                sb.Append(item.c_name);
                sb.Append("</td>");

                sb.Append("<td>");
                sb.Append(item.debit);
                sb.Append("</td>");

                sb.Append("<td>");
                sb.Append(item.debit);
                sb.Append("</td>");

                sb.Append("<td>");
                sb.Append(item.credit);
                sb.Append("</td>");

                sb.Append("<td>");
                sb.Append(item.QMCount);
                sb.Append("</td>");

                sb.Append("<td>");
                sb.Append(item.c_staff);
                sb.Append("</td>");

                sb.Append("<td>");
                sb.Append(item.c_tele);
                sb.Append("</td>");
                 
                sb.Append("</tr>");
            }
            sb.Append("</tbody>");
            sb.Append("</TABLE>");

            return Json(new { success = true, data = sb.ToString() }, JsonRequestBehavior.AllowGet);
        }



        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [SupportFilter]
        public ActionResult PaymentForm(ts_accpay entity)
        {
            if (entity != null && ModelState.IsValid)
            {
                string currentPerson = GetCurrentPerson();
                //entity.CreateTime = DateTime.Now;
                //entity.CreatePerson = currentPerson;

                entity.Id = Result.GetNewId();
                entity.c_type = "付款";
                entity.f_debit = 0;
                entity.i_sign = "正常";
                string returnValue = string.Empty;
                if (m_BLL.Create(ref validationErrors, entity))
                {
                    LogClassModels.WriteServiceLog(Suggestion.InsertSucceed + "，入库退货表的信息的Id为" + entity.Id, "入库退货表"
                        );//写入日志 
                    return Json(Suggestion.InsertSucceed);
                }
                else
                {
                    if (validationErrors != null && validationErrors.Count > 0)
                    {
                        validationErrors.All(a =>
                        {
                            returnValue += a.ErrorMessage;
                            return true;
                        });
                    }
                    LogClassModels.WriteServiceLog(Suggestion.InsertFail + "，入库退货表的信息，" + returnValue, "入库退货表"
                        );//写入日志                      
                    return Json(Suggestion.InsertFail + returnValue); //提示插入失败
                }
            }

            return Json(Suggestion.InsertFail + "，请核对输入的数据的格式"); //提示输入的数据的格式不对 
        }


        /// <summary>
        /// 异步加载数据
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="rows">每页显示的行数</param>
        /// <param name="order">排序字段</param>
        /// <param name="sort">升序asc（默认）还是降序desc</param>
        /// <param name="search">查询条件</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetData(string id, int page, int rows, string order, string sort, string search)
        {

            int total = 0;
            List<ts_accpay> queryData = m_BLL.GetByParam(id, page, rows, order, sort, search, ref total);
            return Json(new datagrid
            {
                total = total,
                rows = queryData.Select(s => new
                {
                    Id = s.Id
					,c_type = s.c_type
					,dt_dt = s.dt_dt
					,i_no = s.i_no
					,c_paymethod = s.c_paymethod
					,c_invno = s.c_invno
					,c_clerk = s.c_clerk
					,f_debit = s.f_debit
					,f_credit = s.f_credit
					,c_comment = s.c_comment
					,i_sign = s.i_sign
					
                }

                    )
            });
        }
        /// <summary>
        /// 查看详细
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [SupportFilter]  
        public ActionResult Details(string id)
        {
            ts_accpay item = m_BLL.GetById(id);
            return View(item);

        }
 
        /// <summary>
        /// 首次创建
        /// </summary>
        /// <returns></returns>
        [SupportFilter]
        public ActionResult Create(string id)
        { 
            
            return View();
        }
        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [SupportFilter]
        public ActionResult Create(ts_accpay entity)
        {           
            if (entity != null && ModelState.IsValid)
            {
                string currentPerson = GetCurrentPerson();
                //entity.CreateTime = DateTime.Now;
                //entity.CreatePerson = currentPerson;
              
                entity.Id = Result.GetNewId();   
                string returnValue = string.Empty;
                if (m_BLL.Create(ref validationErrors, entity))
                {
                    LogClassModels.WriteServiceLog(Suggestion.InsertSucceed  + "，入库退货表的信息的Id为" + entity.Id,"入库退货表"
                        );//写入日志 
                    return Json(Suggestion.InsertSucceed);
                }
                else
                { 
                    if (validationErrors != null && validationErrors.Count > 0)
                    {
                        validationErrors.All(a =>
                        {
                            returnValue += a.ErrorMessage;
                            return true;
                        });
                    }
                    LogClassModels.WriteServiceLog(Suggestion.InsertFail + "，入库退货表的信息，" + returnValue,"入库退货表"
                        );//写入日志                      
                    return Json(Suggestion.InsertFail  + returnValue); //提示插入失败
                }
            }

            return Json(Suggestion.InsertFail + "，请核对输入的数据的格式"); //提示输入的数据的格式不对 
        }
        /// <summary>
        /// 首次编辑
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns></returns> 
        [SupportFilter] 
        public ActionResult Edit(string id)
        {
            ts_accpay item = m_BLL.GetById(id);
            return View(item);
        }
        /// <summary>
        /// 提交编辑信息
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="collection">客户端传回的集合</param>
        /// <returns></returns>
        [HttpPost]
        [SupportFilter]
        public ActionResult Edit(string id, ts_accpay entity)
        {
            if (entity != null && ModelState.IsValid)
            {   //数据校验
            
                string currentPerson = GetCurrentPerson();                 
                //entity.UpdateTime = DateTime.Now;
                //entity.UpdatePerson = currentPerson;
                           
                string returnValue = string.Empty;   
                if (m_BLL.Edit(ref validationErrors, entity))
                {
                    LogClassModels.WriteServiceLog(Suggestion.UpdateSucceed + "，入库退货表信息的Id为" + id,"入库退货表"
                        );//写入日志                           
                    return Json(Suggestion.UpdateSucceed); //提示更新成功 
                }
                else
                { 
                    if (validationErrors != null && validationErrors.Count > 0)
                    {
                        validationErrors.All(a =>
                        {
                            returnValue += a.ErrorMessage;
                            return true;
                        });
                    }
                    LogClassModels.WriteServiceLog(Suggestion.UpdateFail + "，入库退货表信息的Id为" + id + "," + returnValue, "入库退货表"
                        );//写入日志                           
                    return Json(Suggestion.UpdateFail  + returnValue); //提示更新失败
                }
            }
            return Json(Suggestion.UpdateFail + "请核对输入的数据的格式"); //提示输入的数据的格式不对               
          
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>   
        [HttpPost]
        public ActionResult Delete(FormCollection collection)
        {
            string returnValue = string.Empty;
            string[] deleteId = collection["query"].GetString().Split(',');
            if (deleteId != null && deleteId.Length > 0)
            { 
                if (m_BLL.DeleteCollection(ref validationErrors, deleteId))
                {
                    LogClassModels.WriteServiceLog(Suggestion.DeleteSucceed + "，信息的Id为" + string.Join(",", deleteId), "消息"
                        );//删除成功，写入日志
                    return Json("OK");
                }
                else
                {
                    if (validationErrors != null && validationErrors.Count > 0)
                    {
                        validationErrors.All(a =>
                        {
                            returnValue += a.ErrorMessage;
                            return true;
                        });
                    }
                    LogClassModels.WriteServiceLog(Suggestion.DeleteFail + "，信息的Id为" + string.Join(",", deleteId)+ "," + returnValue, "消息"
                        );//删除失败，写入日志
                }
            }
            return Json(returnValue);
        }
     
        IBLL.Its_accpayBLL m_BLL;

        ValidationErrors validationErrors = new ValidationErrors();

        public ts_accpayController()
            : this(new ts_accpayBLL()) { }

        public ts_accpayController(ts_accpayBLL bll)
        {
            m_BLL = bll;
        }
        
    }
}


